package video.background.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import video.background.Controller.ControllerParams.DeleteParams;
import org.springframework.web.multipart.MultipartFile;
import video.background.Controller.ControllerParams.LoginParams;
import video.background.Controller.ControllerParams.SignInParams;
import video.background.Controller.View.UsersView;
import video.background.Dao.*;
import video.background.Model.*;
import video.background.Services.EmailServices;
import video.background.Utils.*;

import javax.mail.MessagingException;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Objects;

/**
 * @program: background
 * @description:
 * @author: hlt
 * @create: 2023-08-08 15:06
 **/
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(tags = "用户信息管理相关接口")
public class UserController {

    private static final String maleAvatar = "https://smart-box-1311261154.cos.ap-nanjing.myqcloud.com/voices/male.png";
    private static final String femaleAvatar = "https://smart-box-1311261154.cos.ap-nanjing.myqcloud.com/voices/female.png";

    @Autowired // bean注入
    private UserDao userDao;

    @Autowired
    private EmailServices emailServices;

    @Autowired
    private UserGroupDao userGroupDao;

    @Autowired
    private FileTableDao fileTableDao;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private MsgUserDao msgUserDao;


//    @PostMapping("/verifyEmail")
//    @ApiOperation("验证邮箱接口")
//    public Result verifyEmail(Long userId){
//        System.out.println("userId: " + userId);
//        if(userId.equals("") || userId == null)
//            return Result.Error("数据不全",null);
//        Users users = userDao.selectById(userId);
//        System.out.println(users);
//        String secret = Encrypt.numEncrypt(userId.toString());
//        String verificationLink = "http://192.168.29.54:8089/verify/backRequestForMail?userId=" + secret;
//        try {
//            emailServices.sendMail(users, verificationLink);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.Error500("请求出错，请与管理员联系", null);
//        }
//        return Result.Success("验证邮件已经发送至您的邮箱，网络可能延迟，请稍后查看您的邮箱！", null);
//    }

    @GetMapping("/selectSelf")
    @ApiOperation("展示个人信息接口")
    public Result selectSelf(@RequestHeader String Authorization) throws Exception {
        if(Authorization == null || Authorization.equals(""))
            return Result.Error("数据不全",null);
        Long userId = JwtUtils.decoderToken(Authorization);
        Users users = userDao.selectById(userId);
        if(users == null) return Result.Error("用户信息未找到！", null);
        UsersView usersView = new UsersView();
        BeanUtils.copyProperties(users, usersView);  // 复制两个类中相同的属性，(Source, Target)
        usersView.setEmail(AESUtils.decrypt(users.getEmail()));
        return Result.Success("请求成功！", usersView);
    }

    @PostMapping("/updateSelf")
    @ApiOperation("修改个人信息接口")
    public Result updateSelf(@RequestHeader String Authorization,@RequestBody UsersView newUsers){
        //解析token
        if(Authorization == null || Authorization.equals(""))
            return Result.Error("申请人数据不全，请检查数据",null);
        Long userId = JwtUtils.decoderToken(Authorization);
        if(userId == null)
            return Result.Error("申请人数据不全，请检查数据",null);
        Long newUserId = newUsers.getUserId();
        Users oldUsers = userDao.selectById(userId);
        if(oldUsers == null || newUserId == null) return Result.Error("用户信息未找到",null);
        if (!Objects.equals(oldUsers.getUserId(), newUserId))
            return Result.Error("您没有权限修改别人信息，请检查数据",null);
        //校验数据是否合法
        if (newUsers.getUserName().equals("") || newUsers.getEmail().equals(""))
            return Result.Error("数据不全",null);
        if(oldUsers.getUserAvatar().equals(maleAvatar) || oldUsers.getUserAvatar().equals(femaleAvatar)
            || oldUsers.getUserAvatar().isEmpty()){
            if(newUsers.getUserGender() == '1'){
                oldUsers.setUserAvatar(maleAvatar);
            }else{
                oldUsers.setUserAvatar(femaleAvatar);
            }
        }
//        oldUsers.setUserAvatar(newUsers.getUserAvatar());
        oldUsers.setUserGender(newUsers.getUserGender());
        oldUsers.setTrade(newUsers.getTrade());
        oldUsers.setUserIntroduction(newUsers.getUserIntroduction());
        oldUsers.setUserName(newUsers.getUserName());
        userDao.updateById(oldUsers);
        return Result.Success("用户信息更新成功！",null);
    }

    @GetMapping("/beforeDeleteSelf")
    @ApiOperation("注销账户前向用户邮箱发送验证码")
    public Result beforeDeleteSelf(@RequestHeader String Authorization) throws Exception {
        if(Authorization == null || Authorization.equals(""))
            return Result.Error("数据不全",null);
        Long userId = JwtUtils.decoderToken(Authorization);
        Users users1 = userDao.selectById(userId);
        if(users1.getVerifyCodeTime() != null){
            if(DateTimeUtils.getTimeBetween(users1.getVerifyCodeTime()) < 60)
                return Result.Error("您的请求过于频繁，请稍后再试！", null);
        }
        String verifyCode = Random.generateString(6);
        Users users = userDao.selectById(userId);
        if (users == null) return Result.Error("用户信息未找到！", null);
        users.setVerifyCodeTime(DateTimeUtils.dateTimeAndSecondToString());
        users.setVerifyCode(verifyCode);
        userDao.updateById(users);
        users.setEmail(AESUtils.decrypt(users.getEmail()));
        emailServices.sendMessageForGiveUp(users, verifyCode);
        return Result.Success("验证码已发送至您的邮箱，5分钟内有效！", null);
    }

    @PostMapping("/deleteSelf")
    @ApiOperation("注销用户信息")
    public Result deleteSelf(@RequestHeader String Authorization,@RequestBody Map<String, String> data){
//        System.out.println(Authorization);
        String verifyCode = data.get("verifyCode");
        if (verifyCode == null || verifyCode.equals("")) return Result.Error("请输入验证码！", null);
//        System.out.println("verifyCode: " + verifyCode);
        //解析token
        if(Authorization == null || Authorization.equals(""))
            return Result.Error("申请人数据不全，请检查数据",null);
        Long userId = JwtUtils.decoderToken(Authorization);
        if(userId == null)
            return Result.Error("申请人数据不全，请检查数据",null);
        LambdaQueryWrapper<Users> ulqw = new LambdaQueryWrapper<>();
        ulqw.eq(Users::getUserId,userId);
        Users users = userDao.selectOne(ulqw);
        // 检查验证码是否正确
        Result result = Verify.VerifyCheck(users,verifyCode);
        if(result.getMsg().equals("验证码正确有效")) {
            //注销
            userDao.deleteById(userId);
            //删除团队信息
            LambdaQueryWrapper<UserGroup> uglqw = new LambdaQueryWrapper<>();
            uglqw.eq(UserGroup::getUserId,userId);
            List<UserGroup> userGroups = userGroupDao.selectList(uglqw);
            for (UserGroup userGroup : userGroups){
                userGroupDao.deleteById(userGroup.getId());
            }
            //删除声纹信息
            LambdaQueryWrapper<FileTable> ftlqw = new LambdaQueryWrapper<>();
            ftlqw.eq(FileTable::getUserId,userId);
            List<FileTable> fileTables = fileTableDao.selectList(ftlqw);
            for (FileTable fileTable : fileTables){
                fileTableDao.deleteById(fileTable.getFeatureId());
            }
            //删除系统消息
            LambdaQueryWrapper<Message> mlqw = new LambdaQueryWrapper<>();
            mlqw.eq(Message::getUserId,userId);
            List<Message> messages = messageDao.selectList(mlqw);
            for (Message message : messages){
                messageDao.deleteById(message.getMessageId());
            }
            LambdaQueryWrapper<MsgUser> mulqw = new LambdaQueryWrapper<>();
            mulqw.eq(MsgUser::getUserId,userId);
            List<MsgUser> msgUsers = msgUserDao.selectList(mulqw);
            for (MsgUser msgUser : msgUsers){
                msgUserDao.deleteById(msgUser.getMsgUserId());
            }
            return Result.Success("注销成功",null);
        }
        return result;
    }

    @PostMapping("/uploadUserAvatar")
    @ApiOperation("用户上传头像的接口")
    public Result uploadUserAvatar(@RequestParam("file") MultipartFile file, @RequestHeader String Authorization){
        Long userId = JwtUtils.decoderToken(Authorization);
        if (file.isEmpty()) return Result.Error("文件为空！", null);
        try {
            String fileName = userId.toString() + ".png";
            String link = TencentCOSUtil.uploadfileFromBin("UsersAvatar", fileName, file);
            // 将数据信息保存在数据库
            Users users = userDao.selectById(userId);
            users.setUserAvatar(link);
            userDao.updateById(users);
            return Result.Success("上传成功！",link);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.Error500("上传失败！",null);
        }
    }


}
